//
//  Status.swift
//  微博个人swift
//
//  Created by 李灏 on 16/2/19.
//  Copyright © 2016年 lh. All rights reserved.
//

import UIKit

class Status: NSObject {
    //微博ID
    var id:Int64 = 0
    
    //微博创建时间
    var created_at:String?
    
    //微博信息内容
    var text:String?
    
    //微博来源
    var source:String? {
        didSet {
            //<a href=\"http://weibo.com/\" rel=\"nofollow\">微博 weibo.com</a>
            // Range<Index> 泛型对象
            //如何声明swift中的rang对象
            //            let range = 0..<10
            let startRange = source?.rangeOfString("\">")
            let endRange = source?.rangeOfString("</a")
            if let range1 = startRange, range2 = endRange {
                let range = range1.endIndex..<range2.startIndex
                //            let ocrange = NSRange(location: 10, length: 10)
                sourceText = source?.substringWithRange(range)
            }
        }
    }
    
    var sourceText: String?
    //用户信息
    var user:User?

    //配图数组
    var pic_urls:[[String:String]]? {
        didSet {
            if let urls = pic_urls where urls.count != 0 {
                //实例化属性
                imageURLs = [NSURL]()
                for item in urls {
                    let urlString = item["thumbnail_pic"]
                    //强制解包相信后台一定能给数据
                    let imageURL = NSURL(string: urlString!)!
                    imageURLs?.append(imageURL)
                }
            }
        }
    }
    
    //计算型属性 可以实现 url类型的转换
    var imageURLs:[NSURL]?
    
    //计算在下载单张图片的时候该下载谁的图片
    //被转发的原创微博中如果有图片  转发微博中就一定不会有图片
    var pictureURLs: [NSURL]? {
        if retweeted_status != nil {
            //转发微博
            return retweeted_status?.imageURLs
        }
        return imageURLs
    }

    //转发微博数据 嵌套在微博字段中
    //如果是原创微博 retweeted_status 不存在
    var retweeted_status:Status?
    
    //使用KVC设置初始值
    init(dict:[String:AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    //过滤
    override func setValue(value: AnyObject?, forUndefinedKey key: String) { }
    //给User属性初始化
    override func setValue(value: AnyObject?, forKey key: String) {
        if key == "user" {
            //将anyobject转为字典
            if let dict = value as? [String:AnyObject]{
                user = User(dict: dict)
                return
            }
        }
        if key == "retweeted_status" {
            //将anyobject转为字典
            if let dict = value as? [String:AnyObject]{
                retweeted_status = Status(dict: dict)
                return
            }
        }

        super.setValue(value, forKey: key)
    }
    

}
